package com.example.letgo.Fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

import android.widget.EditText;
import android.widget.ImageView;

import android.widget.TextView;
import android.widget.Toast;

import com.example.letgo.Application.GridViewWithHeaderAndFooter;
import com.example.letgo.R;
import com.example.letgo.global.Constant;
import com.example.letgo.model.Story;
import com.example.letgo.model.Team;
import com.example.letgo.story.StoryDetailsActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by cc on 2018/2/3.
 */

public class StoryFragment extends Fragment {
    private static StoryFragment instance = null;
    private GridViewWithHeaderAndFooter gridView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private EditText search;

    private ArrayList<Map<String, Object>> lists=new ArrayList<Map<String,Object>>();

    public StoryFragment() {
        // Required empty public constructor
    }

    /**
     * IM需要的返回实例化的对象-hbl
     * @return
     */
    public static StoryFragment getInstance(){
        if (instance==null){
            instance = new StoryFragment();
        }
        return instance;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_story, container, false);
        gridView = (GridViewWithHeaderAndFooter) view.findViewById(R.id.story_gridview);
        search = view.findViewById(R.id.story_search);
        swipeRefreshLayout = view.findViewById(R.id.story_swipe);

        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                        Toast.makeText(getActivity(), "刷新完成 !", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },1000);
            }
        });

        View headView = getActivity().getLayoutInflater().inflate(R.layout.listhead_story, null);
        View footView = getActivity().getLayoutInflater().inflate(R.layout.listfoot,null);
        gridView.addHeaderView(headView,null,false);
        gridView.addFooterView(footView,null,false);

        init();
        intiEditView();
        Log.i("ID",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>    "+ Constant.id);
        return view;
    }

    private void init() {
        OkGo.get("http://119.29.113.114:8080/gogogo/story")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("s",s);
                        Gson gson = new Gson();
                        Type listType = new TypeToken<LinkedList<Story>>(){}.getType();
                        LinkedList<Story> list = gson.fromJson(s, listType);
                        //  调用适配器
                        gridView.setAdapter(new Stroyadapter(list));

                    }
                });
    }

    public class Stroyadapter extends BaseAdapter {

        LinkedList<Story> list;

        public Stroyadapter(LinkedList<Story> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        // Picasso图片加载框架 进行加载
        @SuppressLint("RestrictedApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getActivity().getLayoutInflater().inflate(R.layout.listview_story, null);
                viewHolder.img =  convertView.findViewById(R.id.story_img);
                viewHolder.destination = convertView.findViewById(R.id.story_title);
                viewHolder.describe = convertView.findViewById(R.id.story_introduce);
                viewHolder.type = convertView.findViewById(R.id.type);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //判断获取的json中图片是否为空
            if (TextUtils.isEmpty("http://119.29.113.114:8080/gogogo/"+list.get(position).getStoryImage())){
                Picasso
                        .with(getActivity())
                        .cancelRequest(viewHolder.img);
                viewHolder.img.setImageDrawable(getResources().getDrawable(R.drawable.loading));//当图片为空时显示
            }else {
                //图片加载
                Picasso
                        .with(getActivity())
                        .load("http://119.29.113.114:8080/gogogo/"+list.get(position).getStoryImage())
                        .placeholder(R.drawable.loading)//图片加载中显示
                        .into(viewHolder.img);
            }
            viewHolder.destination.setText(list.get(position).getStoryOverPlace());
            viewHolder.describe.setText(list.get(position).getStoryDescribe());
            viewHolder.type.setText(list.get(position).getStoryType());


            //  为item设置点击事件， 并传递参数
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Bundle bundle = new Bundle();
                    bundle.putString("position", String.valueOf(position));
                    bundle.putInt("storyUserId", list.get(position).getStoryUserId());
                    bundle.putString("storyOverPlace", list.get(position).getStoryOverPlace());
                    bundle.putString("storyDescribe", list.get(position).getStoryDescribe());
                    bundle.putString("storyText1", list.get(position).getStoryText1());
                    bundle.putString("storyText2", list.get(position).getStoryText2());
                    bundle.putString("storyText3", list.get(position).getStoryText3());
                    bundle.putString("storyImg1", "http://119.29.113.114:8080/gogogo/"+list.get(position).getStoryImage());
                    bundle.putString("storyImg2", "http://119.29.113.114:8080/gogogo/"+list.get(position).getStoryImg2());
                    bundle.putString("storyTime", list.get(position).getStoryTime());
                    bundle.putInt("storyUserId", list.get(position).getStoryUserId());

                    Intent produceinfo = new Intent(getActivity(), StoryDetailsActivity.class);
                    produceinfo.putExtras(bundle);
                    startActivity(produceinfo);
                }

            });
            return convertView;
        }
    }

    private void intiEditView() {
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                mAdapter.getFilter().filter(s);
                String searchtext = search.getText().toString();
                Log.i("Tag",searchtext);
                if ( searchtext.equals("")){

                    Log.i("Tag",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

                    init();

                }else {
                    searchinit();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //    搜索时调用 ------------------------------------------------------------------
    private void searchinit(){
        OkGo.get("http://119.29.113.114:8080/gogogo/story")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("s",s);
                        Gson gson = new Gson();
                        Type listType = new TypeToken<LinkedList<Story>>(){}.getType();
                        LinkedList<Story> list = gson.fromJson(s, listType);
                        Map<String, Object>map=new HashMap<String, Object>();
                        lists.clear();
                        for (int i = 0;i<list.size();i++){
                            if (list.get(i).getStoryOverPlace().equals(search.getText().toString())) {

                                String storyOverPlace = list.get(i).getStoryOverPlace();
                                int storyUserId = list.get(i).getStoryUserId();
                                String storyDescribe = list.get(i).getStoryDescribe();
                                String storyImage = "http://119.29.113.114:8080/gogogo/story"+list.get(i).getStoryImage();
                                String storyTime = list.get(i).getStoryTime();
                                String storyText1 = list.get(i).getStoryText1();
                                String storyText2 = list.get(i).getStoryText2();
                                String storyText3 = list.get(i).getStoryText3();
                                String storyImg1 = "http://119.29.113.114:8080/gogogo/story"+list.get(i).getStoryImage();
                                String storyImg2 = "http://119.29.113.114:8080/gogogo/story"+list.get(i).getStoryImg2();

                                map.put("storyOverPlace",storyOverPlace);
                                map.put("storyUserId", storyUserId);
                                map.put("storyDescribe",storyDescribe);
                                map.put("storyImage",storyImage);
                                map.put("storyTime",storyTime);
                                map.put("storyText1",storyText1);
                                map.put("storyText2",storyText2);
                                map.put("storyText3",storyText3);
                                map.put("storyImg1",storyImg1);
                                map.put("storyImg2",storyImg2);
                                lists.add(map);
                            }
                        }
                        //  调用适配器
                        gridView.setAdapter(new Searchadapter());
                    }
                });
    }

    //   搜索 加载的适配器
    public class Searchadapter extends BaseAdapter{

        @Override
        public int getCount() {
            return lists.size();
        }
        @Override
        public Object getItem(int position) {
            if (lists!= null && lists.size() > position) {
                return lists.get(position);
            } else {
                return null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        // Picasso图片加载框架 进行加载
        @SuppressLint("RestrictedApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getActivity().getLayoutInflater().inflate(R.layout.listview_story, null);
                viewHolder.img = convertView.findViewById(R.id.story_img);
                viewHolder.destination = convertView.findViewById(R.id.story_title);
                viewHolder.describe = convertView.findViewById(R.id.story_introduce);


                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //判断获取的json中图片是否为空
            if (TextUtils.isEmpty("http://119.29.113.114:8080/gogogo/"+lists.get(position).get("storyImage").toString())) {
                Picasso
                        .with(getActivity())
                        .cancelRequest(viewHolder.img);
                viewHolder.img.setImageDrawable(getResources().getDrawable(R.drawable.loading));//当图片为空时显示
            } else {
                //图片加载
                Picasso
                        .with(getActivity())
                        .load("http://119.29.113.114:8080/gogogo/"+lists.get(position).get("storyImage").toString())
                        .placeholder(R.drawable.loading)//图片加载中显示
                        .into(viewHolder.img);
            }
            viewHolder.destination.setText(lists.get(position).get("storyOverPlace").toString());
            viewHolder.describe.setText(lists.get(position).get("storyDescribe").toString());
            Toast.makeText(getActivity(), "搜索成功！", Toast.LENGTH_SHORT).show();

            //  为item设置点击事件， 并传递参数
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Bundle bundle = new Bundle();
                    bundle.putString("position", String.valueOf(position));

                    bundle.putInt("storyUserId", Integer.parseInt(lists.get(position).get("storyUserId").toString()));
                    bundle.putString("storyOverPlace", lists.get(position).get("storyOverPlace").toString());
                    bundle.putString("storyTime", lists.get(position).get("storyTime").toString());
                    bundle.putString("storyText1", lists.get(position ).get("storyText1").toString());
                    bundle.putString("storyText2", lists.get(position ).get("storyText2").toString());
                    bundle.putString("storyText3", lists.get(position ).get("storyText3").toString());
                    bundle.putString("storyImg1", "http://119.29.113.114:8080/gogogo/"+lists.get(position).get("storyImage").toString());
                    bundle.putString("storyImg2", "http://119.29.113.114:8080/gogogo/"+lists.get(position ).get("storyImg2").toString());

                    Intent produceinfo = new Intent(getActivity(), StoryDetailsActivity.class);
                    produceinfo.putExtras(bundle);
                    startActivity(produceinfo);
                }

            });
            return convertView;
        }
    }

    final static class ViewHolder {

        TextView destination,type;
        TextView describe;
        ImageView img;
    }
}

